import { Component } from 'react'
import Taro from '@tarojs/taro';
import { connect } from 'react-redux'
import {View, Button, Input} from '@tarojs/components'
import './login.less'
import Head from "../../../components/head/head";
import {accessUserToken} from "../../../actions/user";

// #region 书写注意
//
// 目前 typescript 版本还无法在装饰器模式下将 Props 注入到 Taro.Component 中的 props 属性
// 需要显示声明 connect 的参数类型并通过 interface 的方式指定 Taro.Component 子类的 props
// 这样才能完成类型检查和 IDE 的自动提示
// 使用函数模式则无此限制
// ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796
//
// #endregion

type PageStateProps = {
  user: {},
}

type PageDispatchProps = {
  accessUserToken: (params) => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps & PageState

interface Login {
  props: IProps;
}

// @ts-ignore
@connect(({ user }) => ({
  user
}), (dispatch) => ({
  accessUserToken (params) {
    // @ts-ignore
    return dispatch(accessUserToken(params))
  },
}))
class Login extends Component {

  state = {
    token: '',
  };

  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }

  changeToken(event) {
    console.log('-----event: ', event);
    if (event && event.target) {
      this.setState({ token: event.target.value });
    }
  }

  //验证token
  loginToken() {
    const {token} = this.state;
    if (token) {
      // eslint-disable-next-line @typescript-eslint/no-shadow
      const {accessUserToken} = this.props;
      if (accessUserToken) {
        // @ts-ignore
        accessUserToken({ accesstoken: this.state.token }).then((value) => {
          Taro.redirectTo({ url: '/user/pages/user/user' })
        })
      }
    } else {
      Taro.showToast({ title: '请输入秘钥再进行登录验证!', icon: 'none' })
    }
  }

  render() {
    console.log('-----Login, this.props: ', this.props);

    return (
      <View className='login-body'>
        {
          // @ts-ignore
          <Head />
        }
        <View className='form'>
          <Input
            type='text'
            onInput={(e)=>this.changeToken(e)}
            className='access_input'
            placeholder='请输入accesstoken'
          />
          <Button
            onClick={()=>this.loginToken()}
            className='btn_login'
          >
            登录
          </Button>
        </View>
      </View>)
  }
}

export default Login

